package sz.szsmk.citizencard.util;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sz.szsmk.citizencard.DaggerApplication;

/**
 * Created by Administrator on 2015/12/18.
 */
public class AndroidUtils {



  public static final String TAG = "PushDemoActivity";
  public static final String RESPONSE_METHOD = "method";
  public static final String RESPONSE_CONTENT = "content";
  public static final String RESPONSE_ERRCODE = "errcode";
  protected static final String ACTION_LOGIN = "com.baidu.pushdemo.action.LOGIN";
  public static final String ACTION_MESSAGE = "com.baiud.pushdemo.action.MESSAGE";
  public static final String ACTION_RESPONSE = "bccsclient.action.RESPONSE";
  public static final String ACTION_SHOW_MESSAGE = "bccsclient.action.SHOW_MESSAGE";
  protected static final String EXTRA_ACCESS_TOKEN = "access_token";
  public static final String EXTRA_MESSAGE = "message";

  public static String logStringCache = "";

  // 获取ApiKey
  public static String getMetaValue(Context context, String metaKey) {
    Bundle metaData = null;
    String apiKey = null;
    if (context == null || metaKey == null) {
      return null;
    }
    try {
      ApplicationInfo ai = context.getPackageManager()
              .getApplicationInfo(context.getPackageName(),
                      PackageManager.GET_META_DATA);
      if (null != ai) {
        metaData = ai.metaData;
      }
      if (null != metaData) {
        apiKey = metaData.getString(metaKey);
      }
    } catch (PackageManager.NameNotFoundException e) {

    }
    Log.e("Push Key", "=================:" + apiKey);
    return apiKey;
  }

  // 用share preference来实现是否绑定的开关。在ionBind且成功时设置true，unBind且成功时设置false
  public static boolean hasBind(Context context) {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(context);
    String flag = sp.getString("bind_flag", "");
    if ("ok".equalsIgnoreCase(flag)) {
      return true;
    }
    return false;
  }

  public static void setBind(Context context, boolean flag) {
    String flagStr = "not";
    if (flag) {
      flagStr = "ok";
    }
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("bind_flag", flagStr);
    editor.commit();
  }

  public static List<String> getTagsList(String originalText) {
    if (originalText == null || originalText.equals("")) {
      return null;
    }
    List<String> tags = new ArrayList<String>();
    int indexOfComma = originalText.indexOf(',');
    String tag;
    while (indexOfComma != -1) {
      tag = originalText.substring(0, indexOfComma);
      tags.add(tag);

      originalText = originalText.substring(indexOfComma + 1);
      indexOfComma = originalText.indexOf(',');
    }

    tags.add(originalText);
    return tags;
  }

  public static String getLogText(Context context) {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(context);
    return sp.getString("log_text", "");
  }

  public static void setLogText(Context context, String text) {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("log_text", text);
    editor.commit();
  }


  public static String getAndroidId(Context context){
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(context);

    if(!sp.getString("androidId", "").equals("")){
        return sp.getString("androidId", "");
    }

    String androidId = null;
    try{
      TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      androidId = tm.getDeviceId() ;
    }catch(Exception e){
      androidId = null;
    }
    if(androidId == null || "".equals(androidId)){
      try{
        androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
      }catch(Exception e){
        androidId = null;
      }
    }

    if(androidId == null || "".equals(androidId)){
      WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      WifiInfo info = wifi.getConnectionInfo();
      androidId = info.getMacAddress();
    }
    if(androidId == null || "".equals(androidId)){
      androidId = ACache.get(context).getAsString("androidId");
      if(androidId == null || "".equals(androidId)){
        androidId = getRandomString(16);
        ACache.get(context).put("androidId",androidId);
      }
    }
    //写入sp
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("androidId", androidId);
    editor.commit();
    return androidId;
  }

  public static String getRandomString(int length) { //length表示生成字符串的长度
    String base = "abcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
      int number = random.nextInt(base.length());
      sb.append(base.charAt(number));
    }
    return sb.toString();
  }
  public static String getPhoneNum(Context context){
    String phoneNum = null;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    phoneNum = tm.getLine1Number() ;
    Log.e("getPhoneNum", "====================phoneNum:"+phoneNum);
    return phoneNum;
  }
  public static String getIMEI(Context context){
    String phoneNum = null;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    phoneNum = tm.getDeviceId() ;
    Log.e("getPhoneNum", "====================getIMEI:"+phoneNum);
    return phoneNum;
  }
  public static String getDeviceSoftwareVersion(Context context){
    String phoneNum = null;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    phoneNum = tm.getDeviceSoftwareVersion() ;
    Log.e("getPhoneNum", "====================DeviceSoftwareVersion:"+phoneNum);
    return phoneNum;
  }
  public static int getPhoneType(Context context){
    int phoneNum = 0;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    phoneNum = tm.getPhoneType() ;
    Log.e("getPhoneNum", "====================PhoneType:"+phoneNum);
    return phoneNum;
  }
  public static String getSimCountryIso(Context context){
    String phoneNum = null;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    phoneNum = tm.getSimCountryIso() ;
    Log.e("getPhoneNum", "====================SimCountryIso:"+phoneNum);
    return phoneNum;
  }
  public static String getSimSerialNumber(Context context){
    String phoneNum = null;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    phoneNum = tm.getSimSerialNumber() ;
    Log.e("getPhoneNum", "====================SimSerialNumber:"+phoneNum);
    return phoneNum;
  }
  public static String getSubscriberId(Context context){
    String phoneNum = null;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    phoneNum = tm.getSubscriberId() ;
    Log.e("getPhoneNum", "====================SubscriberId:"+phoneNum);
    return phoneNum;
  }
  //HARDWARE 硬件
  public static String getHardware(Context context){
    String hardware = android.os.Build.HARDWARE;
    Log.e("getPhoneNum", "====================hardware:"+hardware);
    return hardware;
  }
  public static String getHost(Context context){
    String host = android.os.Build.HOST;
    Log.e("getPhoneNum", "====================host:"+host);
    return host;
  }
  public static String getID(Context context){
    String id = android.os.Build.ID;
    Log.e("getPhoneNum", "====================id:"+id);
    return id;
  }
  //MANUFACTURER 生产厂家
  public static String getManufacture(Context context){
    String manufacture = android.os.Build.ID;
    Log.e("getPhoneNum", "====================manufacture:"+manufacture);
    return manufacture;
  }
  //VERSION.SDK SDK版本
  public static String getVERSIONSDK(Context context){
    String sdk=android.os.Build.VERSION.SDK;
    Log.e("getPhoneNum", "====================sdk:"+sdk);
    return sdk;
  }
  //MODEL 机型
  public static String getModel(Context context){
    String model = android.os.Build.MODEL;
    Log.e("getPhoneNum", "====================model:"+model);
    return model;
  }
  public static String getProduct(Context context){
    String poduct = android.os.Build.PRODUCT;
    Log.e("getPhoneNum", "====================poduct:"+poduct);
    return poduct;
  }
  public static String getRadio(Context context){
    String radio = android.os.Build.PRODUCT;
    Log.e("getPhoneNum", "====================radio:"+radio);
    return radio;
  }
  public static String getUser(Context context){
    String user = android.os.Build.USER;
    Log.e("getPhoneNum", "====================user:"+user);
    return user;
  }
  public static String getTime(Context context){
    long time = android.os.Build.TIME;
    Log.e("getPhoneNum", "====================time:"+time);
    return ""+time;
  }
  public static String getType(Context context){
    String type = android.os.Build.TYPE;
    Log.e("getPhoneNum", "====================type:"+type);
    return type;
  }
  //VERSION.RELEASE 固件版本
  public static String getVERSIONRELEASE(Context context){
    String release = android.os.Build.VERSION.RELEASE;
    Log.e("getPhoneNum", "====================release:"+release);
    return release;
  }
  public static String getVersionCodeName(Context context){
    String versionCodeName = android.os.Build.VERSION.RELEASE;
    Log.e("getPhoneNum", "====================versionCodeName:"+versionCodeName);
    return versionCodeName;
  }
  //BOARD 主板
  public static String getBoard(Context context){
    String board = android.os.Build.BOARD;
    Log.e("getPhoneNum", "====================board:"+board);
    return board;
  }
  public static String getBootloader(Context context){
    String bootLoader = android.os.Build.BOOTLOADER;
    Log.e("getPhoneNum", "====================bootLoader:"+bootLoader);
    return bootLoader;
  }
  //BRAND 运营商
  public static String getBrand(Context context){
    String brand = android.os.Build.BRAND;
    Log.e("getPhoneNum", "====================brand:"+brand);
    return brand;
  }
  //DEVICE 驱动
  public static String getDevice(Context context){
    String device = android.os.Build.DEVICE;
    Log.e("getPhoneNum", "====================device:"+device);
    return device;
  }
  //MAC
  public static String getMac(Context context){
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    return info.getMacAddress();
  }

  public static String getOsName(String version){
    String osName = "";
    if(version.startsWith("1.5")){
      osName = "Cupcake";
    } else if(version.startsWith("1.6")){
      osName = "Donut";
    }else if(version.startsWith("2.0")){
      osName = "Eclair";
    }else if(version.startsWith("2.1")){
      osName = "Eclair";
    }else if(version.startsWith("2.2")){
      osName = "Froyo";
    }else if(version.startsWith("2.3")){
      osName = "Gingerbread";
    }else if(version.startsWith("3")){
      osName = "Honeycomb";
    }else if(version.startsWith("4.0")){
      osName = "Ice Cream Sandwich";
    }else if(version.startsWith("4.1")){
      osName = "Jelly Bean";
    }else if(version.startsWith("4.2")){
      osName = "Jelly Bean";
    }else if(version.startsWith("4.3")){
      osName = "Jelly Bean";
    }else if(version.startsWith("4.4")){
      osName = "KitKat";
    } else if(version.startsWith("5")){
      osName = "Lollipop";
    }

    return osName;
  }
  /*public static boolean isCityCardNo(String cardNo) {
      if (StringCommonUtil.isBlank(cardNo)) {
          return false;
      }
      if(cardNo.length() == 16 && isNumber(cardNo)) {
          return true;
      }
      return false ;
  }*/
  public static boolean isNumber(String cardNo){
    Pattern p = Pattern.compile("^(\\d{16})$");

    Matcher m = p.matcher(cardNo);
    return m.matches();
  }
  /*  public static boolean isCardNo(String cardNo){
        if (StringCommonUtil.isBlank(cardNo)) {
            return false;
        }
        Pattern p = Pattern.compile("^([a-zA-Z]|\\d{1})\\d{7}(\\d{1}|[a-zA-Z])$");
        Matcher m = p.matcher(cardNo);
        return m.matches();
    }
*/
  // 判断是否是A卡
    /*public static boolean isCardA(String cardNo) {
        Log.e("kahao", cardNo);
        Log.e("isCardA", "==================:"+cardNo);

        if (StringCommonUtil.isBlank(cardNo)) {
            return false;
        }

        if (cardNo.length() == 16 && isNumber(cardNo) && cardNo.startsWith("215018")) {
            Log.e("kahapo1", cardNo);
            return true;
        } else {
            Log.e("kahao2", cardNo);
            Pattern p = Pattern.compile("^([a|A][0-9a-zA-Z]{8})$");

            Matcher m = p.matcher(cardNo);
            return m.matches();
        }

    }*/

  // 判断是否是B卡
   /* public static boolean isCardB(String cardNo) {
        if (StringCommonUtil.isBlank(cardNo)) {
            return false;
        }
        if (cardNo.length() == 16 && isNumber(cardNo) && !cardNo.startsWith("215018")) {
            return true;
        }
        return false;
    }*/

  public static String getDetailsMapDistance(int distance) {
    if(distance > 1000 ){
      double dis =  Math.round( distance / 100 )/10 ;
      return dis +" 公里";
    }
    return distance+"米";
  }
  public static String getDetailMapDate(int dateTime){
    String temp = "";
    int day = 0;
    int hour = 0;
    int  minute = 0;

    if(dateTime > 24 * 60 * 60 ) {//tian
      day = getDay(dateTime) ;
      int hourtmp = dateTime % (24 * 60 * 60);
      if( hourtmp > 60 * 60 ) {
        hour = getHour(hourtmp);
        int minuteTmp =  hourtmp % ( 60 * 60) ;
        if(minuteTmp > 60 ) {
          minute = getMinute(minuteTmp);
        } else {
          minute = 1;
        }
      }else if( hourtmp > 60 ) {
        minute = getMinute(hourtmp);
      } else {
        minute = 1;
      }

    } else if(dateTime > 60 * 60 ){ //xiaoshi

      hour = getHour(dateTime);
      int minuteTmp =  dateTime % ( 60 * 60) ;
      if(minuteTmp > 60 ) {
        minute = getMinute(minuteTmp);
      } else {
        minute = 1;
      }
    }else if(dateTime > 60 ) {

      minute = getMinute(dateTime);
    } else {
      minute = 1;
    }


    if(day != 0 ){
      temp = day+" 天 ";
      if(hour != 0) {
        temp = temp + hour +"时";
        if(minute != 0) {
          temp = temp + minute+"分";
        }
      } else if(minute != 0){
        temp = temp + hour +" 时 "+ minute+" 分";
      }

    } else if(hour != 0){
      temp = hour +"时";
      if(minute != 0) {
        temp = temp + minute+"分";
      }
    } else {
      temp =  minute+"分";
    }
    return temp;
  }
  public static int getDay(int second){

    return second /  (24 * 60 * 60);
  }
  public static int getHour(int second){

    return second / ( 60 * 60 );
  }
  public static int getMinute(int second){
    return second / 60 ;
  }

  public static String getDoubleValues(double value){
    DecimalFormat df = new DecimalFormat("0.00");
    return df.format(value);
  }

  public static boolean isHaveAlipayGphone( Context context)
  {
    final PackageManager packageManager = context.getPackageManager();
    // 获取所有已安装程序的包信息
    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
    for ( int i = 0; i < pinfo.size(); i++ )
    {
      if(pinfo.get(i).packageName.equalsIgnoreCase("com.eg.android.AlipayGphone"))
        return true;
    }
    return false;
  }

  /**
   * make true current connect service is wifi
   * @param mContext
   * @return
   */
  public static boolean isWifi(Context mContext) {
    ConnectivityManager connectivityManager = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    if (activeNetInfo != null
            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
      return true;
    }
    return false;
  }

  public static String getFormatNumber(String number){
    if(number == null || "".equals(number)){
      return "0.00";
    }
    DecimalFormat df = new DecimalFormat("0.00");
    String xs = df.format(Double.parseDouble(number));
    return xs;
  }



  /*  public static void copyDBToSDcrad(Context context,String evnName)
    {
        String DATABASE_NAME = "sz.szsmk.citizencard.db";

        String oldPath = "data/data/sz.szsmk.citizencard/databases/" + DATABASE_NAME;
        String newPath = FileUtils.getCityCardFileDir(context,evnName) + File.separator + DATABASE_NAME;

        copyFile(oldPath, newPath);
    }
*/
  /**
   * 复制单个文件
   *
   * @param oldPath
   *            String 原文件路径
   * @param newPath
   *            String 复制后路径
   * @return boolean
   */
  public static void copyFile(String oldPath, String newPath)
  {
    try
    {
      int bytesum = 0;
      int byteread = 0;
      File oldfile = new File(oldPath);
      File newfile = new File(newPath);
      if (!newfile.exists())
      {
        newfile.createNewFile();
      }
      if (oldfile.exists())
      { // 文件存在时
        InputStream inStream = new FileInputStream(oldPath); // 读入原文件
        FileOutputStream fs = new FileOutputStream(newPath);
        byte[] buffer = new byte[1444];
        while ((byteread = inStream.read(buffer)) != -1)
        {
          bytesum += byteread; // 字节数 文件大小
          fs.write(buffer, 0, byteread);
        }
        inStream.close();
      }
    }
    catch (Exception e)
    {
      System.out.println("复制单个文件操作出错");
      e.printStackTrace();

    }

  }

  public static String getVersionName(){
    //默认的versionName是""
    String versionName="";
    PackageManager packageManager= DaggerApplication.getIns().getPackageManager();
    String packageName=DaggerApplication.getIns().getPackageName();
    try {
      PackageInfo packageInfo=packageManager.getPackageInfo(packageName,0);
      versionName=packageInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    return versionName;
  }
  public static int getVersionCode(){
    //默认的versionCode是0
    int versionCode=0;
    PackageManager packageManager= DaggerApplication.getIns().getPackageManager();
    String packageName=DaggerApplication.getIns().getPackageName();
    try {
      PackageInfo packageInfo=packageManager.getPackageInfo(packageName,0);
      versionCode=packageInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    return versionCode;
  }

  //判断是否有nfc
  public static boolean hasNfc(Context context){
    boolean bRet=false;
    if(context==null)
      return bRet;
    NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
    NfcAdapter adapter = manager.getDefaultAdapter();
    if (adapter != null && adapter.isEnabled()) {
      // adapter存在，能启用
      bRet=true;
    }
    return bRet;
  }

  public static boolean isTopActivity(String className, Context context) {

    ActivityManager manager = (ActivityManager)
            context.getSystemService(Context.ACTIVITY_SERVICE);

    ComponentName cn = manager.getRunningTasks(1).get(0).topActivity;

    String topActivityName = cn.getClassName();
    return topActivityName.contains(className);

  }


}
